package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;


/**
 * author by itheima
 *
 * @Date 2022/3/7
 * Description
 */
@Service
@Slf4j
public class   GeneratePageServiceImpl implements GeneratePageService {
    /**
     * 生成文章静态页面
     * @param content
     * @param apArticle
     */
    @Autowired
    Configuration configuration;
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    @Qualifier("minIOFileStorageService")
    FileStorageService fileStorageService;

    @Value("${file.minio.prefix}")
    String prefix;

    @Autowired
    ApArticleMapper apArticleMapper;
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            // 1. 获取template 模板对象
            Template template = configuration.getTemplate("article.ftl");
            // 2. 准备用于替换模板的数据
            Map<String,Object> params = new HashMap<>();
            params.put("article",apArticle);
            params.put("content", JSON.parseArray(content,Map.class));
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            params.put("authorApUserId",apAuthor.getUserId());
            // 3. 替换模板  得到替换后的内容
            StringWriter stringWriter = new StringWriter();
            template.process(params,stringWriter);
            // 4. 将替换后的内容  上传到minio
            InputStream in = new ByteArrayInputStream(stringWriter.toString().getBytes());
            String store = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", in);
            // 5. 将minio中html的地址 保存到apArticle的static_url字段上
            apArticle.setStaticUrl(store);
            apArticleMapper.updateById(apArticle);
            log.info("生成静态页成功  ==> {}",store);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成静态页失败    原因:  ==> {}",e.getMessage());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"生成静态页失败");
        }
    }
}
